#!/usr/bin/env python3

import itertools
import os
import signal
import subprocess
import sys
import types
from typing import Tuple

from lib import sanity_check
sanity_check.check_venv(__file__)

TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))

def start_server(run_dev: subprocess.Popen) -> Tuple[bool, str]:
    failure = False
    i = 0

    def on_timer(signum: int, frame: types.FrameType) -> None:
        nonlocal failure, i
        print("{}. Polling run-dev...".format(i))
        i += 1
        if i == 200:
            failure = True
            run_dev.send_signal(signal.SIGINT)
            signal.setitimer(signal.ITIMER_REAL, 0, 0)

    key = "Quit the server with CTRL-C.\n"
    old_handler = signal.signal(signal.SIGALRM, on_timer)
    signal.setitimer(signal.ITIMER_REAL, 0.5, 0.5)
    log1, log2 = itertools.tee(run_dev.stdout)
    if key not in log1:
        failure = True
    elif not failure:
        run_dev.send_signal(signal.SIGINT)
    signal.setitimer(signal.ITIMER_REAL, 0, 0)
    signal.signal(signal.SIGALRM, old_handler)
    return failure, ''.join(log2)

if __name__ == '__main__':
    print("Testing development server start!")

    with subprocess.Popen(
            [os.path.join(TOOLS_DIR, "run-dev.py")],
            bufsize=1,  # line buffered
            stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
            universal_newlines=True) as run_dev:
        failure, log = start_server(run_dev)

    if 'Traceback' in log:
        failure = True

    if failure:
        print("Development server is not working properly:")
        print(log)
        sys.exit(1)
    else:
        print("Development server is working properly.")
        sys.exit(0)
